<template>
  <vxe-grid ref="xGrid" v-bind="gridOptions" :edit-rules="validRules">
    <template #toolbar_buttons>
      <vxe-button type="default" icon="vxe-icon-add" v-if="!$props.isDetail" @click="modalOfGoods.data.show = true">添加货物</vxe-button>
    </template>

    <template #operate="{ row }">
      <a-tooltip placement="top" title="移除货物" v-if="!$props.isDetail">
      <vxe-button
status="danger" icon="vxe-icon-close" size="medium" round
        @click="removeGoodsRow(row)"
        style="font-size: 11px;height: 1.4rem;"/>
      </a-tooltip>
    </template>

    <template #wid_edit="{ row }">
        <a-tree-select
          v-model:value="row.wid"
          show-search
          style="width: 100%"
          :allow-clear="false"
          size="large"
          tree-default-expand-all
          :tree-data="warehouseList"
          :field-names="{
            value: 'ID',
            label: 'name',
            children: 'areaList',
          }"
          tree-node-filter-prop="name"
          @select="(_, node) => row.wName = node.name"
        />
    </template>
    <template #wid_default="{ row, }">
      <span>{{ row.wName }}</span>
    </template>

    <template #qty_edit="{ row }">
      <vxe-input
v-model="row.qty" type="float" min="0" :max="row.qtyOfMax" style="font-weight: bold;font-size: 1.2rem;"
      digits="0" step="1" @change="inputOnChange(row)"/>
    </template>
    <template #qty_edit_default="{row}">
      <b style="font-size: 1.2rem;">{{ row.qty }}</b>
    </template>

    <template #price_edit="{ row }">
      <vxe-input
      v-model="row.price" type="float" min="0" :max="99999" style="font-weight: bold;font-size: 1.2rem;"
      digits="0" step="10" @change="inputOnChange(row)"/>
    </template>
    <template #price_edit_default="{row}">
      <b style="font-size: 1.2rem;">{{ row.price }}</b>
    </template>

    <template #isGift_edit="{ row, }">
      <vxe-switch v-model="row.isGift" :open-value="1" :close-value="2" disabled/>
    </template>
    <template #memo_edit="{ row }">
      <vxe-input v-model="row.memo" type="text" maxlength="10"/>
    </template>
  </vxe-grid>

  <ModalOfGoods
:show="modalOfGoods.data.show"
:query-api="getTableData"
    @on-close="onCloseModalOfGoods"
    @on-close-of-selected="onCloseSelectedModalOfGoods"
    />

    <vxe-modal
v-model="warehouseModal.show" 
title="批量设置仓库/库区"
      ref="xModalOfWarehouse"
      destroy-on-close 
      resize show-zoom esc-closable showFooter
      width="clamp(400px, 100%, 700px)"
      size="medium"
      :lock-scroll="false"
      @confirm="warehouseModalConfirm">
      <a-form-item label="批量选择仓库/库区">
        <a-tree-select
          show-search
          style="width: 100%"
          :allow-clear="false"
          size="large"
          tree-default-expand-all
          :tree-data="warehouseList"
          :field-names="{
            value: 'ID',
            label: 'name',
            children: 'areaList',
          }"
          tree-node-filter-prop="name"
          @select="(_, option) => warehouseModal.data = option"
        />
      </a-form-item>
    </vxe-modal>
</template>
<script lang="tsx" name="GoodsOfEditList" setup>
// import { ShowSearchType } from "and-design-vue";
import __ from 'lodash-es';
import { reactive, ref, toRaw, watch, } from 'vue';
import { VxeGridProps, VxeTablePropTypes, } from 'vxe-table';
import XEUtils from 'xe-utils';
import { goodsListColumns } from './data';
import { getTableData } from "/@/api/wms/goods";
import { WmsWarehouseItem, getListData as getWarehouseListData } from "/@/api/wms/warehouse";
import { ModalOfGoods, } from '/@/components/XModal';

const props = defineProps({
  show: Boolean,
  isDetail: Boolean,
  dataList: {type: [Array<any>, null] as PropType<Array<any> | null>, default: new Array(5),},
})

const modalOfGoods = reactive({
  data: {show: false,}
})
const onCloseModalOfGoods = () => {
  Object.assign(modalOfGoods.data, {show: false,})
}

const onCloseSelectedModalOfGoods = (list: any[]) => {
  if (list.length > 0) {
    let data = list.map(e => {
      return goods2Obj(e)
    })
    pushTableData(data)
  }
  console.log()
  xGrid.value.focus()
}

function goods2Obj(goods:any) {
  let {ID, name, code, cate, unit, specs, barcode, isGift, price} = goods
  return {
    goodsId: ID, wid: null, wName: '',
    name: name, code: code, cate: cate, unit: unit, specs: specs, barcode: barcode, isGift: isGift,
    price: price, qty: 1, amount: 1 * price, memo: '',
  }
}

watch(() => props.dataList, (v1, _) => {
  if (v1 && v1.length > 0) {
    let list = v1.map((e:any) => {
      let {name, code, cate, unit, specs, barcode,} = e.goods
      return {
        goodsId: e.goodsId,
        name: name, code: code, cate: cate, unit: unit, specs: specs, barcode: barcode, isGift: e.isGift,
        price: e.price, qty: e.qty, amount: e.qty * e.price, memo: e.memo,
        wid: e.wid, wName: e?.warehouse?.name,
      }
    })
    pushTableData(list)
  }
})
const enabled = ref(true)
watch(()=>props.isDetail, (v1, _) => {
  if (v1) {
    enabled.value = false
  }
},{immediate: true})

const validRules = ref({
  // blur,change,manual
  wid: [
    { required: true, validator: ({ cellValue, }) => {
      if (!cellValue || cellValue <= 0) {
        return new Error('请选择仓库')
      }
    }},
  ],
  qty: [
    { required: true, validator: ({ cellValue, }) => {
      if (cellValue <= 0) {
        return new Error('数量必须大于0')
      }
    },},
  ],
} as VxeTablePropTypes.EditRules)

const xGrid = ref()
const gridOptions = reactive<VxeGridProps>({
  id: 'goodsListOfOutbound',
  border: false,
  stripe: true,
  // size: 'medium',
  // maxHeight: window.innerHeight - 320,
  keepSource: true,
  loading: false,
  resizable: true,
  showFooter: true,
  showOverflow: false,
  highlightCurrentRow: false,
  highlightHoverRow: true,
  highlightCurrentColumn: true,
  highlightHoverColumn: true,
  // emptyRender: {name: 'NotDataOfSelectGoods', events: {click: ()=> modalOfGoods.data.show = true},},
  rowConfig: {
    useKey: true,
    isCurrent: false,
    isHover: true,
    keyField: 'goodsId',
  },
  columnConfig: {
    useKey: true,
    isCurrent: false,
    isHover: true,
  },
  customConfig: {
    storage: true,
  },
  sortConfig: {
    trigger: 'default',
    remote: false
  },
  filterConfig: {
    remote: false
  },
  mouseConfig: {selected: true},
  keyboardConfig: {
    isArrow: true,
    isEnter: true,
    isDel: false, 
    isTab: true,
    enterToTab: false,
    isEdit: true, 
    isChecked: true,
  },
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    enabled: enabled.value,
    showStatus: false,
    showAsterisk: true,
    autoClear: true,
    beforeEditMethod: ({ row, column, }) => {
      if (row.isGift !== 2 && column.field === 'price') {
        return false
      }
      return true
    }
  },
  toolbarConfig: {
    zoom: false,
    custom: false,
    slots: {
      buttons: 'toolbar_buttons',
      // tools: 'toolbar_right',
    }
  },
  footerMethod: ({columns, data,}) => {
    if (data.length === 0) {
      return []
    }
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '合计'
        }
        if (['qty'].includes(column.field)) {
          let sum = data.reduce((pre, cur,)=>{
            return pre + Number(cur['qty']);
          }, 0)
          return XEUtils.commafy(XEUtils.toNumber(sum), { digits: 1, });
        }
        if (['amount'].includes(column.field)) {
          let sum = data.reduce((pre, cur,)=>{
            return pre + Number(cur['amount']);
          }, 0)
          return XEUtils.commafy(XEUtils.toNumber(sum), { digits: 2, });
        }
        return null
      }),
    ]
  },
  columns: [
  { title: '操作', sortable: false, visible: true, width: 60, align: 'center', fixed: 'left', 
    slots: {default: 'operate', header: ({}) => {
      return (
        // <Popconfirm title="您要移除『全部商品』吗?" ok-text="全部移除"
        // onConfirm={() => removeGoodsRow()}>
        //   <vxe-button status="danger" icon="vxe-icon-close" size="mini" round 
        //   disabled={props.dataList && props.dataList.length <= 1}
        //   title="移除全部商品"
        //   style="font-size: 1px;height: 16px;"/>
        // </Popconfirm>
        <span></span>
      )
    },}
  },
  ...(()=>{
    goodsListColumns.forEach(e => {
      if (e.field === 'wid') {
        e.editRender = { autofocus: '.ant-select-selection-search input', autoselect: false, immediate: true, }
        e.slots = { 
          edit: 'wid_edit', 
          default: 'wid_default',
          header: ({}) => {
            return (<span>
              <b>收货仓库/库区</b>
              {props.isDetail 
              ? <span></span> 
              : <a-button type="link" size="small"
              style="margin-left:10px;font-weight:normal;font-size:0.8rem;"
              title="批量设置仓库"
              onClick={()=>warehouseModal.show=true}>批量</a-button>}
            </span>)
          }
        }
      }
    })
    return [...goodsListColumns]
  })(),
  // ...goodsListColumns,
  ],
  data: [] as any[],
})

// warehouse
const warehouseList = ref<WmsWarehouseItem[]>()
getWarehouseListData().then(dd => {
  warehouseList.value = dd.map(e => {
    return { ...e, selectable: !(e.areaList && e.areaList.length > 0), disabled: e.enable == 2}
  })
})

const warehouseModal = reactive({
  show: false,
  data: null,
})

const warehouseModalConfirm = () => {
  if (!warehouseModal.data) {
    return
  }
  let {fullData} = xGrid.value.getTableData()
  fullData.forEach(e => {
    e.wName = warehouseModal.data?.name
    e.wid = warehouseModal.data?.ID
  })
  xGrid.value.loadData(fullData)
}

// watch(() => {
//   if (xGrid.value) {
//     let {fullData} = xGrid.value.getTableData()
//     return fullData
//   }
//   return []
// }, (v1, _) => {
//   delRowOfOnlyOne.value = (v1.length < 2)
// })

const removeGoodsRow = (row?:any) => {
  // let {fullData} = xGrid.value.getTableData()
  // if (fullData.length < 2) return;
  xGrid.value.remove(row)
}

const inputOnChange = (row:any) => {
  row.qty = XEUtils.toNumber(row.qty)
  row.price = XEUtils.toNumber(row.price)
  row.amount = row.price * row.qty
}

function pushTableData(list:any[]) {
  if (!(list && list.length > 0)) return
  let one:any = null
  if (list.length > 0) {
    one = list[0]
  }
  let {fullData} = xGrid.value.getTableData()
  fullData.forEach((e1:any) => {
    list.forEach((e2:any) => {
      if (e1.goodsId === e2.goodsId && e1.wid === e2.wid) {
        e1.qty++
        e1.amount = e1.qty * e1.price
        __.remove(list, (e3:any) => e1.goodsId === e3.goodsId)
      }
    })
  })
  xGrid.value.loadData(__.concat(fullData, list))

  let axtRow = list[0] ?? fullData[0]
  if (one) axtRow = fullData.find((e:any) => e.goodsId === one.goodsId && e.wid === one.wid) || one
  xGrid.value.setEditCell(axtRow, 'qty')
}

defineExpose({
  getGoodsList: async () => {
    let result = await xGrid.value.fullValidate(true).then(info => {
      if (info) {
        return null
      } else {
        let {fullData} = xGrid.value.getTableData()
        return toRaw(fullData);
      }
    })
    return result
  },
  getTable: () => {
    return xGrid.value
  },
});
</script>

<style scoped>
:deep().vxe-input--prefix-icon{
  display: flex;
  margin: 0 20px;
}
:deep().selectBtn{
  font-size:.8rem;
  /* margin: 0px -9px; */
  margin-right: -9px;
  padding: 0px 12px;
}
:deep().selectBtn:hover{
  background: rgba(220,220,220,.5);
}
:deep().search-goods-input input{
  color:black;
  opacity: .8;
  font-size: .9rem;
  font-weight: bold;
  margin-left: 10px;
}

:deep().vxe-footer--row{
  background: rgba(250,250,250,.6);
  font-weight: bold;
}
</style>
